/*
 * Copyright (c) 2013-2018 上海汇数数据. All rights reserved.
 * @(#) SpringI18nMessage.java 2018-08-06 12:43
 */

package cn.jh.common.core.support.spring;


import cn.jh.common.core.i18n.I18n;
import cn.jh.common.core.i18n.I18nMessage;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;


/**
 * @author Fuchun
 * @since 1.0
 */
public class SpringI18nMessage implements I18nMessage, MessageSourceAware, InitializingBean {

    private MessageSource messageSource;

    public SpringI18nMessage() {
    }

    public SpringI18nMessage(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    @Override
    public void afterPropertiesSet() {
        I18n.setI18nMessage(this);
    }

    @Override
    public String getOrDefault(String code, String defaultMessage) {
        return getOrDefault(code, (Object[]) null, defaultMessage);
    }

    @Override
    public String getOrDefault(String code, @Nullable Object[] args, String defaultMessage) {
        return messageSource.getMessage(code, args, defaultMessage, LocaleContextHolder.getLocale());
    }

    @Override
    public String getOrDefault(String code, Object[] args, Locale locale, String defaultMessage) {
        return messageSource.getMessage(code, args, defaultMessage, locale);
    }

    @Override
    public String get(String code, @Nullable Object[] args, Locale locale) {
        return messageSource.getMessage(code, args, locale);
    }

    @Override
    public String get(String code, @Nullable Object[] args) {
        return get(code, args, LocaleContextHolder.getLocale());
    }

    @Override
    public String get(String code) {
        return get(code, (Object[]) null);
    }

    @Override
    public void setMessageSource(MessageSource messageSource) {
        this.messageSource = messageSource;
    }
}
